package model;

import java.sql.Date;

import javax.swing.table.AbstractTableModel;

import dao.tables.PERSONNE;

public class JTablePersonneModel extends AbstractTableModel {
    private static final long serialVersionUID = 2534199402037550177L;

    PERSONNE[] data = null;
    String[] titles = null;

    public boolean isCellEditable(int row, int col) {
	if (col == 0) {
	    return false;
	} else {
	    return true;
	}
    }

    public JTablePersonneModel(PERSONNE[] personnes, String[] titles) {
	this.data = personnes;
	this.titles = titles;
    }

    public int getColumnCount() {
	return titles.length;
    }

    public int getRowCount() {
	return data.length;
    }

    public Object getValueAt(int row, int col) {
	switch (col) {
	case 0:
	    return data[row].getId();
	case 1:
	    return data[row].getCivilite();
	case 2:
	    return data[row].getNom();
	case 3:
	    return data[row].getPrenom();
	case 4:
	    return data[row].getDateDeNaissance();
	default:
	    return null;
	}
    }

    @Override
    public void setValueAt(Object obj, int row, int col) {
	switch (col) {
	case 0:
	    data[row].setId((Long) obj);
	    break;
	case 1:
	    data[row].setCivilite((String) obj);
	    break;
	case 2:
	    data[row].setNom((String) obj);
	    break;
	case 3:
	    data[row].setPrenom((String) obj);
	    break;
	case 4:
	    data[row].setDateDeNaissance((Date) obj);
	    break;
	}
    }

    public PERSONNE getPersonneAt(int row) {
	return data[row];
    }

    public void sePersonneAt(PERSONNE obj, int row) {
	data[row] = obj;
    }

    public void addPersonne(PERSONNE personne) {
	PERSONNE[] dataTmp = new PERSONNE[data.length + 1];
	dataTmp[data.length] = personne;
	data = dataTmp;
	dataTmp = null;
	this.fireTableRowsInserted(data.length, data.length);
    }

    public void removePersonneAt(int row) {
	PERSONNE[] dataTmp = new PERSONNE[data.length - 1];
	for (int i = 0; i < data.length; i++) {
	    if (i < row)
		dataTmp[i] = data[i];
	    else if (i > row)
		dataTmp[i - 1] = data[i];
	}
	data = dataTmp;
	dataTmp = null;
	this.fireTableRowsDeleted(row - 1, row - 1);
    }

    @Override
    public String getColumnName(int col) {
	return titles[col];
    }
}
